<template>
  <div class="home">
    <div id="map" class="map-home"></div>
  </div>
</template>

<script>
// 图上图标相关
import OlFeature from "ol/Feature";
import OlGeomPoint from "ol/geom/Point";
import OlLayerVector from "ol/layer/Vector";
import OlSourceVector from "ol/source/Vector";
import OlOverlay from "ol/Overlay";
// import  from "ol/geom/Polygon";
import { transform, fromLonLat } from "ol/proj";
import ol, { Map, View, Feature } from "ol";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { XYZ, Vector as VectorSource } from "ol/source";
import * as olProj from "ol/proj";
import { Point, Polygon } from "ol/geom";
import { Style, Fill, Stroke, Circle as sCircle } from "ol/style";
import { defaults, FullScreen, MousePosition, ScaleLine } from "ol/control";
import Overlay from "ol/Overlay"; //显示要素
import { Draw } from "ol/interaction";
import { boundingExtent } from "ol/extent";
import { Icon } from "ol/style";
import { loadFeaturesXhr } from "ol/featureloader";
import { computeAttributesStride } from "ol/webgl/Helper";

export default {
  name: "Home",
  components: {},
  props: ["centerPos", "wdPos", "line"],
  data() {
    return {
      vector_points: {},
      fitView: [],
      markerArr: [],
      openMap: null,
      source: null,
      pointSource: null,
      // drawLayer: null,
      pointSources: null,
    };
  },

  mounted() {
    // this.aa()
  },
  methods: {
    aa() {
      let _this = this;

      this.initMap(); //加载地图
      console.log(this.wdPos, "wdPos");
      console.log("log");

      if (this.wdPos) {
        // this.centerIcons(this.wdPos);

        this.wdPos.forEach((element) => {
          this.fitView.push(...element.pos);
          console.log(element);
          this.centerIcons(element);
        //   this.settext(element);
        });

        for (var i = 0; i < this.line.length; i++) {
          this.pointSources.addFeature(this.line[i]);
        }

        var extent = boundingExtent([
          [...olProj.transform(this.wdPos[0].pos, "EPSG:4326", "EPSG:3857")],
          [...olProj.transform(this.wdPos[1].pos, "EPSG:4326", "EPSG:3857")],
        ]);

        this.openMap.getView().fit(extent, this.openMap.getSize());
      }

    //   this.mapEvent();
    },
    initMap() {
      this.openMap = new Map({
        target: "map",
        layers: [
          new TileLayer({
            source: new XYZ({
              url: "http://222.79.63.193:8077/mapImg/1/V1/{z}/{x}/{y}.png",
            }),
          }),
        ],
        view: new View({
          // 将福州作为地图中心
          // center: olProj.fromLonLat([119.27345, 26.04769]),
          center: olProj.fromLonLat(
            this.centerPos ? this.centerPos : this.wdPos[0].pos
          ),
          // center: olProj.fromLonLat([100, 50]),
          zoom: 15, // 缩放级别
          minZoom: 0, // 最小缩放级别
          maxZoom: 18, // 最大缩放级别
          constrainResolution: true,
        }),

        controls: defaults().extend([
          // new FullScreen(), // 全屏
          // new MousePosition(), // 显示鼠标当前位置的经纬度
          // new ScaleLine()// 显示比例尺
        ]),
      });

      //创建两个图层 用来存放地图上得图标 第一个是网点  第二个是定位图标
      this.pointSources = new OlSourceVector();
      var vector_points = new OlLayerVector({
        source: this.pointSources,
        zIndex: 2,
      });
      this.vector_points = vector_points;
      this.openMap.addLayer(vector_points);
      this.pointSource = new OlSourceVector();
      var vector_point = new OlLayerVector({
        source: this.pointSource,
        zIndex: 2,
      });
      this.openMap.addLayer(vector_point);

      this.source = new XYZ({
        url: "http://222.79.63.193:8077/mapImg/1/V1/{z}/{x}/{y}.png",
      });
    },

    mapEvent() {
      let _this = this;
      this.openMap.on("singleclick", function (evt) {
        // console.log(evt);
        var feature = _this.openMap.forEachFeatureAtPixel(
          evt.pixel,
          function (feature) {
            return feature;
          }
        );

        console.log(feature);
        if (feature) {
          console.log(feature.value, 139);
        //   _this.settext(feature.value);
        }
      });
    },
    //设置中心坐标
    centerIcon(positionData) {
      //设置地图的地位图标
      Location = olProj.transform(positionData, "EPSG:4326", "EPSG:3857");
      var point = new OlFeature(new OlGeomPoint(Location));
      point.setStyle(
        new Style({
          image: new Icon({
            src: require("../../../assets/images/orderTracking/icon_jijiandan.png"),
            anchor: [0.5, 1],
          }),
        })
      );

      this.pointSource.clear();
      this.source.clear();
      this.pointSource.addFeature(point);
      this.openMap.getView().setZoom(15);
    },

    // 网点信息窗体
    addPopupFun() {},
    //设置网点得图标
    centerIcons(positionData) {
      //设置地图的地位图标
      let positionDatas = [119.298641, 51.420347];

      let Locations = olProj.transform(
        positionData.pos,
        "EPSG:4326",
        "EPSG:3857"
      );

      let points = new OlFeature(new OlGeomPoint(Locations));

      points.value = positionData;
      if (positionData.name == "my") {
        points.setStyle(
          new Style({
            image: new Icon({
              src: require("../../../assets/images/orderTracking/icon_jijiandan.png"),
              anchor: [0.5, 1],
            }),
          })
        );
      } else {
        points.setStyle(
          new Style({
            image: new Icon({
              src: require("../../../assets/images/orderTracking/icon_shoujiandan.png"),
              anchor: [0.5, 1],
            }),
          })
        );
      }
      this.pointSource.clear();
      this.source.clear();
      this.pointSources.addFeature(points);
      this.openMap.getView().setZoom(13);
    },
    //放置文字函数

    settext(positionData, id) {
      console.log(positionData, 206);
      let goodsInfoHTML = "";
      positionData.goodInfo.forEach((t) => {
        if (t.goodsName == "我在这里") {
          goodsInfoHTML = "我在这里";
        } else {
          goodsInfoHTML += t.goodsName + "," + t.goodsNumber + ";";
        }
      });

      let _this = this;
      let Locations = olProj.transform(
        positionData.pos,
        "EPSG:4326",
        "EPSG:3857"
      );

      let el = document.createElement("div");
      el.className = "popupId";

      let marker = new Overlay({
        element: el, // 要显示的元素
        position: Locations, // 地图投影的位置
        offset: [-35, -75], // 元素显示的像素偏移量
        autoPan: true, // 自动移动地图以完整的显示元素
      });
      marker.pos = positionData.pos.join();
      let has = this.markerArr.findIndex((t) => {
        return t.pos == marker.pos;
      });

      if (has >= 0) return;

      this.markerArr.push(marker);

      let closeDom = document.createElement("span");
      let context = document.createElement("span");
      if (!goodsInfoHTML.trim()) {
        goodsInfoHTML = "无信息";
      }
      context.innerHTML = goodsInfoHTML;
      closeDom.className = "closePopup";
      closeDom.innerHTML = "X";
      closeDom.addEventListener("click", function (e) {
        e.target.parentNode.parentNode.remove();

        let ishas = _this.markerArr.findIndex((t) => {
          return t.pos == marker.pos;
        });

        _this.markerArr.splice(ishas, 1);
      });
      el.appendChild(closeDom);
      el.appendChild(context);

      // 添加到地图
      this.openMap.addOverlay(marker);
    },
  },
};
</script>
<style lang="scss" scoped>
.map-home {
  width: 100vw;
  height: 100%;
}
</style>
<style >
.popupId {
  height: 32px;
  min-width: 1rem;
  position: relative;
  border-radius: 10px;
  background-color: rgba(0, 0, 0, 0.8);
  line-height: 32px;
  text-align: center;
  color: #fff;
  padding: 0.1rem;
}
.closePopup {
  line-height: 20px;
  height: 20px;
  width: 20px;
  position: absolute;
  top: -10px;
  right: -10px;
  color: #c4c4c4;
  background-color: #fff;
  border-radius: 50%;
  text-align: center;
}
.ol-zoom.ol-unselectable.ol-control {
  display: none;
}
.ol-rotate.ol-unselectable.ol-control.ol-hidden {
  display: none;
}
</style>